const state = {
    stageList: [], // 获取所有学段数据
    regionList: [], // 区域数据
    regionMap: {}, // 市区县key-children数据
    stageSubjectList: [] // 学段学科
};

const getters = {};

const actions = {
    // 获取所有学段数据
    getStageList({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            if(state.stageList.length) {
                resolve(state.stageList);
                return;
            }
            dispatch('proxyAction', {
                name: 'stagesList',
                queries: {
                    withAllStage: false
                }
            }, {root: true}).then((res) => {
                let data = res.data || [];

                commit('meta', {
                    stageList: data
                })
                resolve(data)
            }).catch((err) => {
                reject(err)
            })
        })
    },
    // 获取所有学段学科的数据
    getStageRefSubject({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            if(state.stageSubjectList.length) {
                resolve(state.stageSubjectList);
                return;
            }

            dispatch('proxyAction', {
                name: 'listStageRefSubject',
                queries: {
                    withAllStage: false,
                    withAllSubject: false,
                    withMultipleStage: false
                }
            }, {root: true}).then((res) => {
                let data = res.data || [];

                commit('meta', {
                    stageSubjectList: data
                })
                resolve(data)
            }).catch((err) => {
                reject(err)
            })
        })
    },
    // 获取省市区县
    getRegionList( {commit, state, dispatch}, pid ) {
        
        return new Promise((resolve, reject) => {
            if(pid == 0 && state.regionList.length) {
                resolve(state.regionList);
                return;
            }
            if(pid !== 0 && state.regionMap[pid] && state.regionMap[pid].length) {
                resolve(state.regionMap[pid]);
                return;
            }
            dispatch('proxyAction', {
                name: 'regionList',
                data: {
                   pid
                }
            }, {root: true}).then(res => {
                commit('SET_REGION', [pid, res.data])
                resolve(res.data || [])
            }).catch((err) => {
                reject(err)
            })
        })
    }
};

const mutations = {
    'meta': (state, data) => {
        console.log(state, data, '==========')
        Object.assign(state, data);
    },
    'SET_REGION': (state, [pid, data]) => {
        console.log(1111111111);
        state.regionMap[pid] = data
    }
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}
